const util = require('util');
const debug = util.debuglog('oil-game:luckDraw:action');

const {
    getOwnBoxInfo,    // 获取幸运抽奖
    addLuckDrawNum,   // 增加抽奖次数
    getLuckDrawInfo,    // 获取幸运抽奖
    reduceLuckDrawNum,    //减少抽奖次数
    savePrize,    //暂存用户抽奖结果
    getPrize,   //获取用户抽奖结果
} = require('./cache');
const {
    Msg,
    VIDEO_ADD_NUM,    //看视频增加抽奖多少次数
    PushRoute,    // 客户端需要监听的接口
    JACKPOT,    //奖池
} = require('./consts');
const {
    addCoins,   //增加金币
    addOil,   //增加石油
    addIncomeRate,    //采集收入加速
} = require('./api');

//打开抽奖页面
exports.openLuckDraw = async function (uid) {
    debug("uid = %s 获取抽奖次数", uid);
    //获取幸运抽奖
    let luckDraw = await getLuckDrawInfo.call(this, uid);
    return luckDraw && luckDraw.luckDrawNum;
}

//视频增加抽奖次数
exports.addLuckDrawNum = async function (uid) {
    debug("uid = %s 视频增加抽奖次数", uid);
    //判断抽奖次数是否为零
    let luckDraw = await getLuckDrawInfo.call(this, uid);
    if (!(luckDraw && luckDraw.luckDrawNum == 0)) {
        debug("uid = %s luckDraw = %s 视频增加抽奖次数异常，当前抽奖次数不为零", uid, JSON.stringify(luckDraw));
        throw new Error(Msg.NUM_IS_NOT_NULL);
    }
    //增加抽奖次数
    await addLuckDrawNum.call(this, uid, VIDEO_ADD_NUM);
}

//开始抽奖
exports.startLuckDraw = async function (session) {
    let {uid} = session;
    //判断抽奖次数
    let {luckDrawNum} = await getLuckDrawInfo.call(this, uid);
    debug("uid = %s luckDrawNum = %s 开始抽奖", uid, luckDrawNum);
    if (luckDrawNum < 1) {
        debug("uid = %s  luckDrawNum = %s  开始抽奖次数不足", uid, luckDrawNum);
        throw new Error(Msg.NUM_IS_NULL);
    }
    //获取奖品
    let prizeIndex = Math.floor(Math.random() * JACKPOT.length);
    let prize = JACKPOT[prizeIndex];
    //暂存用户抽奖结果
    await savePrize.call(this, uid, prize);
    return prize;
}

//抽奖结束，更新奖品
exports.endLuckDraw = async function (session) {
    let {uid} = session;
    //从缓存中获取抽奖结果
    let prize = await getPrize.call(this, uid);
    //减少抽奖次数
    await reduceLuckDrawNum.call(this, uid);

    switch (prize.type) {
        case "oil":
            await addOil.call(this, session, prize.num);
            break;
        case "coins":
            await addCoins.call(this, session, prize.num);
            break;
        case "speedUp":
            await addIncomeRate.call(this, session, prize.num);
            break;
    }
}
